package com.example.weight.wormHandle.cultivate;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.MyAdapter;
import com.example.weight.config.Config;
import com.example.weight.wormHandle.cultivate.HatchingIncoming;
import com.example.weight.wormHandle.cultivate.HatchingIncoming;
import com.example.weight.util.WeightActivity;
import com.example.weight.wormHandle.garbageDisposal.researchDevelopment.BatchGroupNumber;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.Locale.filter;

public class HatchingIncoming extends AppCompatActivity {
    private EditText tv_group_number,tv_box_number,et_fermentMaterial_weight,
            tv_material_name,et_worm_weight,et_material_weight,et_bug_material_weight,et_water_weight,et_sum_weight;
    private TextView tv_start_date, tv_number;
    private Spinner batchGroupNumber;
    private List<BatchGroupNumber> batchGroupNumberList;

    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    private String name, factory;
    private String activeButton = "";
    private BatchGroupNumber belongTo_id;

    //    主料及辅料及虫卵来源
    private String fermentMaterial_name = "", material_name = "", source_name = "";
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy");

    //备注
    private EditText remark;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hatching_incoming);
//        批次
//        tv_number = findViewById(R.id.tv_number);
//        tv_number.setText("P"+simpleDateFormat2.format(new Date()));

//        tv_group_number = findViewById(R.id.tv_group_number);
        tv_box_number = findViewById(R.id.tv_box_number);
//        et_box_weight = findViewById(R.id.et_box_weight);
//        主料选择
        RadioGroup fermentMaterial_radioGroup = (RadioGroup)findViewById(R.id.zhuliao_group_button);
        fermentMaterial_radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton fermentMaterial_radioButton = (RadioButton)findViewById(fermentMaterial_radioGroup.getCheckedRadioButtonId());
                fermentMaterial_name = fermentMaterial_radioButton.getText().toString();
            }
        });

//        tv_fermentMaterial_kind = findViewById(R.id.tv_fermentMaterial_kind);
//        主料重量
        et_fermentMaterial_weight = findViewById(R.id.et_fermentMaterial_weight);
//        辅料选择
        RadioGroup material_radioGroup = (RadioGroup)findViewById(R.id.fuliao_group_button);
        material_radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton material_radioButton = (RadioButton)findViewById(material_radioGroup.getCheckedRadioButtonId());
                material_name = material_radioButton.getText().toString();
            }
        });
//        tv_material_name = findViewById(R.id.tv_material_name);
//        辅料重量
        et_material_weight = findViewById(R.id.et_material_weight);
//        虫卵重量
        et_worm_weight = findViewById(R.id.et_worm_weight);
        et_bug_material_weight = findViewById(R.id.et_bug_material_weight);
//        et_bug_material_weight.setHint("-");
        et_water_weight = findViewById(R.id.et_water_weight);
        et_sum_weight = findViewById(R.id.et_sum_weight);
//        et_sum_weight.setHint("-");
        //下拉框
        batchGroupNumber = findViewById(R.id.sp_primary_key);
        batchGroupNumberList = new ArrayList<>();

//        虫卵来源
        RadioGroup source_radioGroup = (RadioGroup)findViewById(R.id.source_group_button);
        source_radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton material_radioButton = (RadioButton)findViewById(source_radioGroup.getCheckedRadioButtonId());
                source_name = material_radioButton.getText().toString();
            }
        });
//        remark = findViewById(R.id.remark);
        TitleBar titleBar = findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                HatchingIncoming.this.finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        tv_start_date = findViewById(R.id.tv_start_date);
        tv_start_date.setText(simpleDateFormat.format(new Date()));
        tv_start_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(HatchingIncoming.this, 2, tv_start_date, calendar);
            }
        });
        Pattern p = Pattern.compile("\\d+");

//        RequestQueue queue = Volley.newRequestQueue(this);
//        String url = Config.url + "/hsmpy/hatchingFeed/getlatest" + "?factory=" + factory;
//        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        try {
//                            JSONObject jsonObject = new JSONObject(response);
//                            JSONArray data1 = jsonObject.getJSONArray("data");
//                            JSONObject data = data1.getJSONObject(0);
//                            Log.d("jy", data.toString());
//                            if (!data.isNull("id")) {
////                                tv_start_date.setText(data.getString("hatchStartTime"));
////                                tv_number.setText(data.getString("batch"));
////                                tv_group_number.setHint(data.getString("wormGroup"));
//                                Matcher m = p.matcher(data.getString("hatchBoxNumber"));
//                                m.find();
//                                tv_box_number.setHint(m.group());
////                                et_box_weight.setHint(data.getString("hatchBoxWeight"));
//                                if(data.getString("fermentMaterialType").equals("发酵料")){//代表发酵料
//                                    fermentMaterial_radioGroup.check(R.id.zhuliao1);
//                                }else if(data.getString("fermentMaterialType").equals("餐厨")){//代表餐厨
//                                    fermentMaterial_radioGroup.check(R.id.zhuliao2);
//                                }
////                                tv_fermentMaterial_kind.setText(data.getString("fermentMaterialType"));
//                                et_fermentMaterial_weight.setHint(data.getString("fermentMaterialWeight"));
////                                tv_material_name.setText(data.getString("fuliaoName"));
//                                if(data.getString("fuliaoName").equals("锯末")){//代表锯末
//                                    material_radioGroup.check(R.id.fuliao1);
//                                }else if(data.getString("fuliaoName").equals("麸皮")){//代表麸皮
//                                    material_radioGroup.check(R.id.fuliao2);
//                                }
//                                if(data.getString("remark").equals("外购")){//代表外购
//                                    source_radioGroup.check(R.id.source1);
//                                }else if(data.getString("remark").equals("自产")){//代表自产
//                                    source_radioGroup.check(R.id.source2);
//                                }
//                                et_material_weight.setHint(data.getString("fuliaoWeight"));
////                                et_bug_material_weight.setHint(data.getString("chongluanfuliaoWeight"));
//                                et_sum_weight.setHint(data.getString("clfpslbwWeight"));
//                                et_water_weight.setHint(data.getString("waterWeight"));
//                                et_worm_weight.setHint(data.getString("eggWeight"));
////                                remark.setHint(data.getString("remark"));
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(HatchingIncoming.this,
//                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        });
//        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//        queue.add(stringRequest);

        //获取1-3待填写的批次、组别、孵化盒号列表
        RequestQueue queue = Volley.newRequestQueue(this);
        String url2 = Config.url + "/hsmpy/hatchWorm/getlist" + "?factory=" + factory;
        StringRequest stringRequest2 = new StringRequest(Request.Method.GET, url2,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                Log.d("jy", data.toString());
                                if( data.length()>0){
                                    for (int i=0; i < data.length(); i++){
                                        JSONObject record = data.getJSONObject(i);
                                        batchGroupNumberList.add(new BatchGroupNumber(record.getInt("id"),record.getString("batch"),record.getString("wormGroup"),record.getString("temp4"),"",record.getString("eggWeight"),record.getString("date")));
                                    }
                                    Log.d("jy", batchGroupNumberList.toString());
                                    ArrayAdapter<BatchGroupNumber> adapter = new ArrayAdapter<BatchGroupNumber>(HatchingIncoming.this, android.R.layout.simple_spinner_item,batchGroupNumberList);
                                    batchGroupNumber.setAdapter(adapter);
                                    batchGroupNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            belongTo_id = batchGroupNumberList.get(position);
                                            et_worm_weight.setText(belongTo_id.getEggWeight());
                                        }

                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {
                                            belongTo_id = null;
                                        }
                                    });
                                    batchGroupNumber.setSelection(0,true);
                                }else {
                                    Toast.makeText(HatchingIncoming.this, "没有可操作的数据", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(HatchingIncoming.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest2.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest2);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
//            case "btn_get_box_weight":
//                et_box_weight.setText(weight);
//                break;
            case "btn_get_fermentMaterial_weight":
                et_fermentMaterial_weight.setText(weight);
                break;
            case "btn_get_material_weight":
                et_material_weight.setText(weight);
                break;
            case "btn_get_water_weight":
                et_water_weight.setText(weight);
                break;
            case "btn_get_worm_weight":
                et_worm_weight.setText(weight);
                break;
            case "btn_get_sum_weight":
                et_sum_weight.setText(weight);
                break;
            case "btn_get_bug_material_weight":
                et_bug_material_weight.setText(weight);
                break;
            default:
                break;
        }
    }

    public void goWeight(View view) {
        switch (view.getId()) {
//            case R.id.btn_get_box_weight:
//                activeButton = "btn_get_box_weight";
//                break;
            case R.id.btn_get_fermentMaterial_weight:
                activeButton = "btn_get_fermentMaterial_weight";
                break;
            case R.id.btn_get_material_weight:
                activeButton = "btn_get_material_weight";
                break;
            case R.id.btn_get_water_weight:
                activeButton = "btn_get_water_weight";
                break;
            case R.id.btn_get_worm_weight:
                activeButton = "btn_get_worm_weight";
                break;
            case R.id.btn_get_sum_weight:
                activeButton = "btn_get_sum_weight";
                break;
            case R.id.btn_get_bug_material_weight:
                activeButton = "btn_get_bug_material_weight";
                break;
            default:
                break;
        }
        Intent intent = new Intent(HatchingIncoming.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }


    public void submit(View view){
//        if (tv_number.getText().toString().equals("")) {
//            Toast.makeText(this, "请填写批次", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        if (tv_group_number.getText().toString().equals("")) {
//            Toast.makeText(this, "请填写组别", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (belongTo_id == null) {
            Toast.makeText(this, "请选择批次、组别、孵化盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tv_box_number.getText().toString().equals("")) {
            Toast.makeText(this, "请填写孵化盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        if(tv_start_date.getText().toString().equals("")) {
            Toast.makeText(this, "请填写孵化开始日期", Toast.LENGTH_SHORT).show();
            return;
        }

//        if(et_sum_weight.getText().toString().equals("")){
//            et_sum_weight.setText("0");
////            return;
//        }
//        if(et_bug_material_weight.getText().toString().equals("")){
//            et_bug_material_weight.setText("0");
////            return;
//        }
//        if(tv_fermentMaterial_kind.getText().toString().equals("")){
//            Toast.makeText(this, "请填写发酵料种类", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if(tv_start_date.getText().toString().equals("")) {
            Toast.makeText(this, "请填写孵化开始日期", Toast.LENGTH_SHORT).show();
            return;
        }
//        if(et_box_weight.getText().toString().equals("")){
//            Toast.makeText(this, "请填写孵化盒重", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if(fermentMaterial_name.equals("")){
            Toast.makeText(this, "请选择主料种类", Toast.LENGTH_SHORT).show();
            return;
        }
//        if(et_fermentMaterial_weight.getText().toString().equals("")) {
//            Toast.makeText(this, "请填写发酵料重量", Toast.LENGTH_SHORT).show();
//            return;
//        }

//        if(et_bug_material_weight.getText().toString().equals("")){
//            Toast.makeText(this, "请填写虫卵辅料重量", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if(et_water_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写水重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_worm_weight.getText().toString().equals("")){
            Toast.makeText(this, "请填写虫卵重量", Toast.LENGTH_SHORT).show();
            return;
        }
//        if(et_sum_weight.getText().toString().equals("")){
//            Toast.makeText(this, "请填写总重量", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if(source_name.equals("")){
            Toast.makeText(this, "请选择虫卵来源", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {

                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/hsmpy/hatchingFeed/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    //Toast.makeText(RepairTable.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2"))
                                            Toast.makeText(HatchingIncoming.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(HatchingIncoming.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(HatchingIncoming.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("jy", error.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map = new HashMap<>();
                            map.put("hatch_start_time",tv_start_date.getText().toString());
                            map.put("batch",belongTo_id.getBatch());
                            map.put("worm_group", belongTo_id.getGroup());
                            map.put("serial", belongTo_id.getNumber());
//                            String hatch_box_number = ;
                            map.put("hatch_box_number", "W"+tv_box_number.getText().toString());
//                            System.out.println(tv_number.getText().toString().getClass());
//                            map.put("hatch_box_weight", "666");
                            map.put("ferment_material_type", fermentMaterial_name);
                            map.put("ferment_material_weight",et_fermentMaterial_weight.getText().toString());
                            map.put("fuliao_name", material_name);
                            map.put("fuliao_weight", et_material_weight.getText().toString());
                            if(et_bug_material_weight.getText().toString().equals("")){
                                map.put("chongluanfuliao_weight", "0");
                            }else {
                                map.put("chongluanfuliao_weight", et_bug_material_weight.getText().toString());
                            }
                            if(et_sum_weight.getText().toString().equals("")){
                                map.put("clfpslbw_weight", "0");
                            }else {
                                map.put("clfpslbw_weight", et_sum_weight.getText().toString());
                            }
                            map.put("water_weight", et_water_weight.getText().toString());
                            map.put("egg_weight", et_worm_weight.getText().toString());
//                            map.put("clfpslbw_weight", et_sum_weight.getText().toString());
                            map.put("remark", source_name);
                            map.put("factory", factory);
                            Log.d("jy",map.toString());
//                            Log.d("factory",factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

}